//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using CommunityServer.Components;
using CommunityServer.Controls;
using CommunityServer.ControlPanel.UI;
using System.Collections.Specialized;

namespace CommunityServer.ControlPanel.Tools
{
	/// <summary>
	/// Summary description for ManageLicenses.
	/// </summary>
	public class ManageLicenses : BaseToolsPage
	{
		#region Members

		protected System.Web.UI.WebControls.Repeater Products;
		protected StatusMessage Status;
		protected System.Web.UI.HtmlControls.HtmlInputFile LicenseFile;
		protected Button UploadLicense;

		Hashtable currentLicenses = null;

		#endregion

		override protected void OnInit(EventArgs e)
		{
			base.OnInit(e);

			Products.ItemDataBound += new RepeaterItemEventHandler(Products_ItemDataBound);
			UploadLicense.Click += new System.EventHandler(UploadLicense_Click);
			this.Load += new System.EventHandler(this.Page_Load);

			try
			{
				currentLicenses = Telligent.Registration.Licensing.GetCurrentLicenses();
			}
			catch (Exception)// ex)
			{
				throw new CSException(CSExceptionType.LicenseAccessError, "An error occured while retrieving license information"); //, ex);
			}
		}


		private void Page_Load(object sender, System.EventArgs e)
		{
			DataBind();
		}

		public override void DataBind()
		{
			UploadLicense.Text = ControlPanel.Components.ResourceManager.GetString("CP_Tools_ManageLicenses_Install");

			Products.DataSource = GetProductsList();
			Products.DataBind();
		}

		#region Product List Retrieval Method

		private ArrayList GetProductsList()
		{
			ArrayList products;
			Hashtable licenseKeys = new Hashtable();

			try
			{
				products = CommunityServer.Components.Products.GetProducts();

				foreach (store_Product product in products)
				{
					if (!Globals.IsNullorEmpty(product.LicenseType))
						licenseKeys[product.LicenseType] = true;
				}
			}
			catch
			{
				// if an error occurs while loading the product list from the web service, retrieve the listing from the currently-installed licenses
				if (!Status.Visible)
				{
					Status.Success = false;
					Status.IsLicenseMessage = true;
					Status.Text = ControlPanel.Components.ResourceManager.GetString("CP_Tools_ManageLicenses_ProductsCouldNotBeRetrieved");
					Status.Visible = true;
				}

				products = new ArrayList();
			}

			store_Product p;
			foreach (string key in currentLicenses.Keys)
			{
				if (!licenseKeys.ContainsKey(key))
				{
					Telligent.Registration.LicenseInfo licenseInfo = (Telligent.Registration.LicenseInfo)currentLicenses[key];
					p = new store_Product();
					p.Name = licenseInfo.Name;
					p.LicenseType = key;

					p.Description = String.Empty;
					p.Price = -1;
					p.ProductURL = String.Empty;

					products.Add(p);
					licenseKeys[key] = true;
				}
			}
			

			return products;
		}

		#endregion

		#region Event Handlers

		private void UploadLicense_Click(Object sender, System.EventArgs e)
		{
			if (LicenseFile.PostedFile == null || LicenseFile.PostedFile.ContentLength == 0 || LicenseFile.PostedFile.FileName.ToUpper().IndexOf(".XML") == -1)
			{
				Status.Success = false;
				Status.IsLicenseMessage = false;
				Status.Text = ControlPanel.Components.ResourceManager.GetString("CP_Tools_ManageLicenses_InvalidLicenseFile");
				Status.Visible = true;
				return;
			}

			try
			{
				byte[] content = new byte[LicenseFile.PostedFile.ContentLength];
				LicenseFile.PostedFile.InputStream.Read(content, 0, LicenseFile.PostedFile.ContentLength);
				System.Text.Encoding encoding = new System.Text.UTF8Encoding(true, true);
				string license = encoding.GetString(content).Trim();				

				Telligent.Registration.Licensing.UpdateLicense(license);

				Status.Success = true;
				Status.IsLicenseMessage = false;
				Status.Text = ControlPanel.Components.ResourceManager.GetString("CP_Tools_ManageLicenses_LicenseInstalled");
				Status.Visible = true;

				try
				{
					currentLicenses = Telligent.Registration.Licensing.GetCurrentLicenses();
				}
				catch (Exception)// ex)
				{
					throw new CSException(CSExceptionType.LicenseAccessError, "An error occured while retrieving license information"); //, ex);
				}

				DataBind();
			}
			catch(CSException ex)
			{
				Status.Success = false;
				Status.IsLicenseMessage = false;
				if(ex.InnerException == null)
					Status.Text = String.Format(ControlPanel.Components.ResourceManager.GetString("CP_Tools_ManageLicenses_LicenseError"), ex.Message);
				else
					Status.Text = String.Format(ControlPanel.Components.ResourceManager.GetString("CP_Tools_ManageLicenses_LicenseError"), ex.InnerException.Message);
				Status.Visible = true;
			}
		}

		private void Products_ItemDataBound(Object sender, RepeaterItemEventArgs e) 
		{
			switch ( e.Item.ItemType ) 
			{
				case ListItemType.Item:
				case ListItemType.AlternatingItem:

					store_Product product = (store_Product) e.Item.DataItem;

					HyperLink productName = (HyperLink) e.Item.FindControl("ProductName");
					Literal productDescription = (Literal) e.Item.FindControl("ProductDescription");
					Literal productLicenseInstalled = (Literal) e.Item.FindControl("ProductLicenseInstalled");

					HyperLink moreInformation = (HyperLink) e.Item.FindControl("MoreInformation");
					HyperLink purchase = (HyperLink) e.Item.FindControl("Purchase");
					HyperLink support = (HyperLink) e.Item.FindControl("Support");

					productName.Text = product.Name == null ? "&nbsp;" : product.Name;
					productName.NavigateUrl = product.ProductURL == null ? String.Empty : product.ProductURL;
					productName.Target = "_blank";

					productDescription.Text = Globals.IsNullorEmpty(product.SecondaryDescription) ? String.Empty : product.SecondaryDescription;

					bool isLicensed = false;
					if (Globals.IsNullorEmpty(product.LicenseType))
					{
						productLicenseInstalled.Text = "&nbsp;";
						isLicensed = true;
					}
					else
					{
						object license = currentLicenses[product.LicenseType];
						if (license != null)
						{
							Telligent.Registration.LicenseInfo licenseInfo = (Telligent.Registration.LicenseInfo) license;

							string licenseLevel = (licenseInfo.Level != null) ? licenseInfo.Level : string.Empty;
							string prodLevel = (licenseInfo.Level != null) ? licenseInfo.Level : string.Empty;
							if (licenseLevel.IndexOf(":") != -1)
							{
								prodLevel = licenseLevel.Substring(licenseLevel.IndexOf(":") + 1);
								licenseLevel = licenseLevel.Substring(0, licenseLevel.IndexOf(":"));
							}

							if (Globals.IsNullorEmpty(product.Level) || prodLevel.IndexOf(product.Level) != -1)
							{
								isLicensed = true;

								if (!Globals.IsNullorEmpty(licenseLevel))
									productLicenseInstalled.Text = ResourceManager.GetString("Yes") + " (" + licenseLevel + ", v" + licenseInfo.Version + ")";
								else
									productLicenseInstalled.Text = ResourceManager.GetString("Yes") + " (v" + licenseInfo.Version + ")";
							
								if (licenseInfo.Expires != DateTime.MinValue)
									productLicenseInstalled.Text += "<br />" + string.Format(ControlPanel.Components.ResourceManager.GetString("CP_Tools_ManageLicenses_LicenseExpires"), licenseInfo.Expires.ToShortDateString());
							}
							else
								productLicenseInstalled.Text = ResourceManager.GetString("No");
						}
						else
							productLicenseInstalled.Text = ResourceManager.GetString("No");
					}

					if (!Globals.IsNullorEmpty(product.ProductURL))
					{
						moreInformation.Text = ControlPanel.Components.ResourceManager.GetString("CP_Tools_ManageLicenses_MoreInformation");
						moreInformation.NavigateUrl = product.ProductURL;
					}
					else
					{
						moreInformation.Visible = false;
						if (e.Item.FindControl("MoreInformationDelimiter") != null)
							e.Item.FindControl("MoreInformationDelimiter").Visible = false;
					}

					if (!Globals.IsNullorEmpty(product.PurchaseURL))
					{
						purchase.Text = ControlPanel.Components.ResourceManager.GetString("CP_Tools_ManageLicenses_Purchase");
						purchase.NavigateUrl = product.PurchaseURL;
					}
					else
					{
						purchase.Visible = false;
						if (e.Item.FindControl("PurchaseDelimiter") != null)
							e.Item.FindControl("PurchaseDelimiter").Visible = false;
					}

					if (!Globals.IsNullorEmpty(product.SupportURL) && isLicensed)
					{
						support.Text = ControlPanel.Components.ResourceManager.GetString("CP_Tools_ManageLicenses_Support");
						support.NavigateUrl = product.SupportURL;
					}
					else
					{
						support.Visible = false;
						if (e.Item.FindControl("SupportDelimiter") != null)
							e.Item.FindControl("SupportDelimiter").Visible = false;
					}

					break;
			}
		}

		#endregion
	}
}
